package cn.lg.soar.mvc.filter;

import cn.lg.soar.common.util.IpUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * IP 黑名单
 * @author luguoxiang
 * @date 2022/9/5
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class IpBlacklistFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(IpBlacklistFilter.class);

    private final Set<Integer> ips;

    public IpBlacklistFilter(Collection<String> ips) {
        Assert.notEmpty(ips, "ips must not be empty");
        this.ips = ips.stream().map(IpUtil::ip4vToInt).collect(Collectors.toSet());
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        int remoteIpInt = IpUtil.getRemoteIpInt(httpRequest);

        if (ips.contains(remoteIpInt)) {
            String ip = IpUtil.intIpToIpv4(remoteIpInt);
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "IP not allowed: " + ip);
            logger.warn("Blocked request due to IP in blacklist: {}", ip);
        } else {
            chain.doFilter(request, response);
        }
    }

}